package com.formiaomiao.demain.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.util.List;

/**
 * 单张图片上传工具类
 */
@Component
public class QiniuUtil {
    private static final Logger logger = LoggerFactory.getLogger(QiniuUtil.class);

    Gson gson = new Gson();


    private String accessKey = "6b03gE5vVFbsgZD8f7w7e_fLLhUMiE9XI7gU1u6c";

    private String secretKey = "8alTuWYlg1g_HSxJ_cCB8GobikMtmJuNEoCHxxLM";

    private String bucket = "demian";

    private String path = "idv093d.qiniudns.com";

    /**
     * 将图片上传到七牛云
     *
     * @param file
     * @param key  保存在空间中的名字，如果为空会使用文件的hash值为文件名
     * @return
     */
    public String uploadImg(FileInputStream file, String key) throws QiniuException {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        Response response = uploadManager.put(file, key, upToken, null, null);
        //解析上传成功的结果
        DefaultPutRet putRet = gson.fromJson(response.bodyString(), DefaultPutRet.class);
        String return_path = "http://hxs.bfzhang.cn/" + putRet.key;
        logger.info("保存地址={}", return_path);
        return auth.privateDownloadUrl(return_path, 3600 * 365 * 10)+","+putRet.key;
    }

    /**
     * 删除七牛云图片
     *
     * @param imgid
     * @return
     */
    public String deleteImg(String imgid) throws QiniuException {
        Auth auth = Auth.create(accessKey, secretKey);
        Configuration config = new Configuration(Zone.zone0());
        BucketManager bucketMgr = new BucketManager(auth, config);
        Response response = bucketMgr.delete(bucket, imgid);
        if (response.bodyString().contains("200")) {
            return "七牛云删除成功";
        } else {
            return "七牛云删除失败";
        }
    }
}
